//
//  HWOpenVipFunctionAlert.swift
//  HWanGame
//
//  Created by 王昌健 on 2021/12/9.
//  Copyright © 2021 94Wan. All rights reserved.
//

import UIKit
import WebKit

class HWOpenVipFunctionAlert: MMPopupView {
    private var tapBgView:UIView!
    private var bgView: UIView!
    
    /// 标题背景
    var titleBgImageView:UIImageView!
    /// 标题
    var titleLabel:UILabel!
    /// 权益说明
    var explainTitle:UILabel!
    /// 权益说明内容
    var explainContent:UILabel!
    /// 权益展示
    var exhibitionTitle:UILabel!
    /// 权益展示内容
    var exhibitionWeb:WKWebView!
    /// 关闭
    var closeButton:UIButton!
    
    var model:HWOpenVipFuncAlertInfo? {
        didSet {
            titleLabel.text = model?.title
            explainTitle.text = model?.title_1
            explainContent.text = model?.content_1
            exhibitionTitle.text = model?.title_2
            exhibitionWeb.load(URLRequest(url: URL(string: model?.content_2 ?? "")!))
        }
    }
    
    var closeButtonClick:(()->())?
    var jumpToVipCenter:(()->())?
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initUI()
        
        initFrame()
        
        addAction()
        
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
    }
    override func hide() {
        super.hide()
        
    }
}
extension HWOpenVipFunctionAlert {
    private func initUI() -> Void {
        type = MMPopupType.alert
        backgroundColor = UIColor.clear
        attachedView = UIApplication.shared.windows.filter({ $0.isKeyWindow }).last?.rootViewController?.view
        tapBgView = UIView.init()
        tapBgView.backgroundColor = UIColor.clear
        addSubview(tapBgView)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(bacgroundTap(_:)))
        tapBgView.addGestureRecognizer(tap)
        
        bgView = UIView.init()
        bgView.backgroundColor = .white
        bgView.layer.cornerRadius = 10
        addSubview(bgView)
        
        titleBgImageView = UIImageView()
        titleBgImageView.image = UIImage(named: "vipAlertTitleBg")
        bgView.addSubview(titleBgImageView)
        
        titleLabel = HWLabel.createBoldLabel(title: "VIP开通", color: "#333333", font: 14*widthScale)
        titleLabel.font = UIFont.init(name: "YouSheBiaoTiHei", size: 22*widthScale)!
        titleBgImageView.addSubview(titleLabel)
        
        explainTitle = HWLabel.createBoldLabel(title: "权益说明", color: "#CCAC64", font: 14*widthScale)
        bgView.addSubview(explainTitle)
        
        explainContent = HWLabel.createLabel(title: "为VIP用户专设的游戏礼包，海量礼包等您来领取，达到VIP1即可解锁", color: "#999999", font: 12*widthScale)
        bgView.addSubview(explainContent)
        
        exhibitionTitle = HWLabel.createBoldLabel(title: "权益展示", color: "#CCAC64", font: 14*widthScale)
        bgView.addSubview(exhibitionTitle)
        
//        let userContent = WKUserContentController()
//        userContent.add(self, name: "go")
//        let config = WKWebViewConfiguration()
//        config.userContentController = userContent
        
        exhibitionWeb = WKWebView()
//        exhibitionWeb.configuration.userContentController.add(self, name: "go")
        exhibitionWeb.navigationDelegate = self
        exhibitionWeb.uiDelegate = self
        exhibitionWeb.scrollView.showsVerticalScrollIndicator = false
        exhibitionWeb.scrollView.bounces = false
        bgView.addSubview(exhibitionWeb)
        
        
        
        closeButton = UIButton(type: .custom)
        closeButton.setImage(UIImage(named: "openVipAlertClose"), for: .normal)
        closeButton.addTarget(self, action: #selector(rejectButtonClick(_:)), for: .touchUpInside)
        bgView.addSubview(closeButton)
        
    }
    
    private func initFrame() -> Void {
        snp.makeConstraints { make in
            make.width.equalTo(screenWidth)
            make.height.equalTo(screenHeight)
        }
        
        tapBgView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalTo(0)
        }
        
        bgView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(31*widthScale)
            make.right.equalTo(-31*widthScale)
            
        }
        
        titleBgImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(titleBgImageView.snp.width).multipliedBy(0.186)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        explainTitle.snp.makeConstraints { make in
            make.left.equalTo(14*widthScale)
            make.top.equalTo(titleBgImageView.snp.bottom).offset(16*widthScale)
        }
        
        explainContent.snp.makeConstraints { make in
            make.left.equalTo(14*widthScale)
            make.right.equalTo(-14*widthScale)
            make.top.equalTo(explainTitle.snp.bottom).offset(10*widthScale)
        }
        
        exhibitionTitle.snp.makeConstraints { make in
            make.left.equalTo(14*widthScale)
            make.top.equalTo(explainContent.snp.bottom).offset(22*widthScale)
        }
        
        exhibitionWeb.snp.makeConstraints { make in
            make.left.equalTo(14*widthScale)
            make.right.equalTo(-14*widthScale)
            make.top.equalTo(exhibitionTitle.snp.bottom).offset(10*widthScale)
            make.height.equalTo(0)
            make.bottom.equalTo(-30*widthScale)
        }
        
        closeButton.snp.makeConstraints { make in
            make.top.equalTo(bgView.snp.bottom).offset(20*widthScale)
            make.centerX.equalToSuperview()
        }
        
        
    }
}
extension HWOpenVipFunctionAlert {
    @objc func bacgroundTap(_ tap:UITapGestureRecognizer) -> Void {
        
        hide()
        
    }
    
    @objc func rejectButtonClick(_ button:UIButton) -> Void {
        hide()
        closeButtonClick?()
    }
    
    
    func addAction() -> Void {
        
    }
    
}

extension HWOpenVipFunctionAlert:UITextViewDelegate{
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString == "userAgreement" {
            print("用户协议")
            return false
        }else if URL.absoluteString == "privacyPolicy" {
            print("隐私政策")
            return false
        }else {
            return true
        }
        
    }
}

extension HWOpenVipFunctionAlert:WKNavigationDelegate,WKUIDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        weak var weakSelf = self
        webView.evaluateJavaScript("Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight)") { (result, error) in
            if result == nil { return }
            
            var height = result as! CGFloat
            if height >= screenHeight/2 - 10{
                height = screenHeight/2 - 10
            }
            weakSelf?.exhibitionWeb.snp.updateConstraints({ make in
                make.height.equalTo(height)
            })
        }
    }
    
    

//    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
//
//    {
//
//        if(message.name == "go") {
//
//
//        }
//
//    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        if message == "go" {
            self.hide()
            self.jumpToVipCenter?()
        }
        completionHandler()
    }
}
